var Mi18nAdmin = {
  admin: {
    login: function() {
      var data = {
        username: $('#login-box .form input[name="username"]').val(),
        password: $('#login-box .form input[name="password"]').val()
      };
      $.post('./api.php?action=login', data, function(result) {
        var result = JSON.parse(result);
        if (result.status == '200') {
          $('#login-box').fadeOut();
          Mi18nAdmin.language.getList(1);
        } else if (result.status == '500') {
          $('#login-box .result').text(result.message);
          $('#login-box .result').fadeIn();
        }
      });
    },
    deleteAdmin: function(el, id) {
      var _this = this;
      $.get('./api.php?action=deleteAdmin&id=' + id, function(result) {
        result = JSON.parse(result);
        if (result.status == '200') {
          $(el).siblings('.result').text(result.message);
        } else {
          $(el).siblings('.result').text(result.message);
        }
        $(el).fadeIn()
        setTimeout(function() {
          $(el).siblings('.result').fadeOut();
          _this.manage();
        }, 5000);
      });
    },
    addAdmin: function(el) {
      var _this = this;
      var data = {
        'username': $(el).siblings('input[name="username"]').val(),
        'password': $(el).siblings('input[name="password"]').val(),
        'repassword': $(el).siblings('input[name="repassword"]').val()
      }
      if (data.password != data.repassword) {
        $(el).siblings('.result').text('密码与确认密码不一致');
        $(el).siblings('.result').fadeIn();
        setTimeout(function() {
          $(el).siblings('.result').fadeOut();
        }, 5000);
        return;
      }
      $.post('./api.php?action=addAdmin', data, function(result) {
        result = JSON.parse(result);
        if (result.status == '200') {
          $(el).siblings('.result').text(result.message);
        } else {
          $(el).siblings('.result').text(result.message);
        }
        $(el).siblings('.result').fadeIn();
        setTimeout(function() {
          $(el).siblings('.result').fadeOut();
          _this.manage();
        }, 5000);
      });
    },
    changePassword: function(el) {
      var _this = this;
      var data = {
        'id': $(el).siblings('input[name="id"]').val(),
        'oldPassword': $(el).siblings('input[name="oldPassword"]').val(),
        'newPassword': $(el).siblings('input[name="newPassword"]').val()
      }
      $.post('./api.php?action=changePassword', data, function(result) {
        result = JSON.parse(result);
        if (result.status == '200') {
          $.get('./api.php?action=logout', function(result) {
            result = JSON.parse(result);
            if (result == 'true') {
              $(el).siblings('.result').text(result.message);
              $(el).siblings('.result').fadeIn();
              setTimeout(function() {
                $(el).siblings('.result').fadeOut();
                window.location.reload();
              }, 3000);
            }
          });
        } else if (result.status == '500') {
          $(el).siblings('.result').text(result.message);
        }
        $(el).siblings('.result').fadeIn();
        setTimeout(function() {
          $(el).siblings('.result').fadeOut();
        }, 5000);
      });
    },
    manage: function() {
      var _this = this;
      $('.admin').show();
      $('.admin dd ul').html('<li>载入中......</li>');
      $.get('./api.php?action=getAdmin', function(result) {
        _this.result = JSON.parse(result);
        var html = '';
        for (var i in _this.result) {
          html += '<li>';
          html += _this.result[i].username + ' <input name="id" type="hidden" value="' + _this.result[i].id +
            '" /><input name="oldPassword" placeholder="原密码" type="password" />&nbsp;<input name="newPassword" placeholder="新密码" type="password" />&nbsp;<input type="button" class="change-password" value="修改密码" />';
          if (_this.result[i].username != 'admin') {
            html += '&nbsp;<a href="#none" class="delete-admin">删除</a>';
          }
          html += '<span class="result"></span></li>';
        }
        $('.admin dd ul').html(html);
        // 修改密码
        $('.admin dd ul li .change-password').off('click').click(function() {
          _this.changePassword(this);
        });
        // 添加管理员
        $('.admin .add-admin-box input[type="button"]').off('click').click(function() {
          _this.addAdmin(this);
        });
        // 删除管理员
        $('.admin dd ul li .delete-admin').off('click').click(function() {
          _this.deleteAdmin(this, $(this).siblings('input[name="id"]').val());
        });
      });
      $('.admin .close, .admin .background').click(function() {
        $('.admin').hide();
      });
    },
    init: function() {
      var _this = this;
      $.get('./api.php?action=isLogin', function(result) {
        result = JSON.parse(result);
        if (result.status == '200') {
          $('#login-box').fadeOut();
        }
      });
      $('#login-box .login-button').click(function() {
        _this.login();
      });
      $('nav .logout-button').click(function() {
        $.get('./api.php?action=logout', function(result) {
          result = JSON.parse(result);
          if (result.status == '200') {
            $('#login-box').fadeIn();
          }
        });
      });
      $('nav .nav-admin').click(function() {
        _this.manage();
      });
    }
  },
  website: {
    init: function() {
      var _this = this;
      $('.website dd ul').html('');
      $.get('./api.php?action=getWebsite', function(result) {
        _this.result = JSON.parse(result);
        $('.website dd ul').html('');
        for (var i in _this.result) {
          $('.website dd ul').append('<li>编号:' + _this.result[i].id +
            ' - 域名: <input type="text" data-set-id="' + _this.result[i].id + '" class="domain" value="' +
            _this.result[i].domain +
            '" />&nbsp;&nbsp;<i class="status"></i><span class="handle"><a href="#none" class="fa fa-trash-o delete-button"></a></span></li>'
          );
        }

        $('.website dd ul li .delete').click(function() {
          var _this = this;
          $.get('./api.php?action=deleteWebsite', function(result) {
            result = JSON.parse(result);
            if (result.status == '200') {
              $(_this).siblings('.status').text('已删除');
            } else {
              $(_this).siblings('.status').text('删除失败');
            }
            setTimeout(function() {
              $(_this).siblings('.status').fadeOut();
            }, 5000);
          });
        });
        $('.website dd ul li .domain').change(function() {
          var _this = this;
          $.post('./api.php?action=updateWebsite', {
            'id': $(this).attr('data-set-id'),
            'domain': $(this).val()
          }, function(result) {
            result = JSON.parse(result);
            if (result.status == '200') {
              $(_this).siblings('.status').text('修改完成').show();
            } else {
              $(_this).siblings('.status').text('修改失败').show();
            }
            setTimeout(function() {
              $(_this).siblings('.status').fadeOut();
            }, 5000);
          });
        });
      });
      $('.website').show();
      $('.website .close, .website .background').click(function() {
        $('.website').hide();
      });
    }
  },
  languageManage: {
    init: function() {
      var __this = _this = this;
      $('.language-manage dd ul').html('');
      $.get('./api.php?action=getLanguage', function(result) {
        _this.result = JSON.parse(result);
        $('.language-manage dd ul').html('');
        if (_this.result.length > 0) {
          for (var i in _this.result) {
            $('.language-manage dd ul').append('<li>索引：<strong>' + _this.result[i].index +
              '</strong> 名称：<input type="text" data-set-index="' + _this.result[i].index +
              '" class="n" value="' + _this.result[i].name +
              '" />&nbsp;&nbsp;<i class="status"></i><span class="handle"><a href="#none" class="fa fa-trash-o delete-button" data-set-index="' +
              _this.result[i].index + '"></a></span></li>');
          }
        }

        $('.language-manage dd ul li .delete-button').click(function() {
          var _this = this;
          var r = confirm("确定删除此语种吗？");
          if (r != true) {
            return;
          }
          $.get('./api.php?action=deleteLanguage&index=' + $(this).attr('data-set-index'), function(
            result) {
            result = JSON.parse(result);
            if (result.status == '200') {
              $(_this).parent().siblings('.status').text(result.message);
              __this.init();
            } else {
              $(_this).parent().siblings('.status').text(result.message);
            }
            setTimeout(function() {
              $(_this).parent().siblings('.status').fadeOut();
            }, 5000);
          });
        });
        $('.language-manage dd ul li .name').change(function() {
          var _this = this;
          $.post('./api.php?action=updateLanguage', {
            'index': $(this).siblings('input[name="index"]').val(),
            'name': $(this).siblings('input[name="name"]').val()
          }, function(result) {
            result = JSON.parse(result);
            if (result.status == '200') {
              $(_this).siblings('.status').text(result.message).show();
              __this.init();
            } else {
              $(_this).siblings('.status').text(result.message).show();
            }
            setTimeout(function() {
              $(_this).parent().siblings('.status').fadeOut();
            }, 5000);
          });
        });
        $('.language-manage .add .add-button').off('click').on('click', function() {
          var _this = this;
          $.post('./api.php?action=addLanguage', {
            'index': $(this).siblings('input[name="index"]').val(),
            'name': $(this).siblings('input[name="name"]').val()
          }, function(result) {
            result = JSON.parse(result);
            if (result.status == '200') {
              $(_this).siblings('.status').text(result.message).show();
              $(_this).siblings('input[name="index"]').val('');
              $(_this).siblings('input[name="name"]').val('');
              __this.init();
            } else {
              $(_this).siblings('.status').text(result.message).show();
            }
            setTimeout(function() {
              $(_this).siblings('.status').fadeOut();
            }, 5000);
          });
        });
      });
      $('.language-manage').show();
      $('.language-manage .close, .language-manage .background').click(function() {
        $('.language-manage').hide();
      });
    }
  },
  language: {
    expandColumn: ['en'],
    searchField: {
      'key': '索引',
      'source': '源文',
      'page': '所属URL'
    },
    languageIndex: {
      'source': '源文'
      /*
      'zh': '中文',
      'ja': '日文',
      'ko': '韩文',
      'en': '英文',
      'fr': '法文',
      'es': '西班牙文',
      'de': '德文'
      */
    },
    search: {
      field: '',
      sc: ''
    },
    // 编辑翻译内容
    edit: function(data) {
      var _this = this;
      $('.content .edit').show();
      $('.content .edit .text dl .index').text(data.attr('data-set-key'));
      $('.content .edit .text dl .language').text(data.attr('data-set-language'));
      $('.content .edit .text dl .page').attr('href', data.attr('data-set-page')).text(data.attr(
        'data-set-page'));
      $('.content .edit .text dl .created-datetime').text(data.attr('data-set-created-datetime'));
      $('.content .edit .text dl .last-update-datetime').text(data.attr('data-set-last-update-datetime'));
      if (data.attr('data-set-action') == 'preview') {
        $('.content .edit .text dl textarea').attr('disabled', 'disabled');
      }
      $('.content .edit .text dl textarea').val(data.val());
      $('.content .edit .text dl textarea').attr('data-set-key', data.attr('data-set-key'));
      $('.content .edit .text dl textarea').attr('data-set-language', data.attr('data-set-language'));

      // 关闭翻译弹出层
      $('.content .edit .background, .content .edit .text dl dt .close').off('click').on('click', function() {
        $('.content .edit').hide();
        var el = $('.content .edit .text dl textarea');
        _this.update(el);
      });

      $('.content .edit .text dl textarea').change(function() {
        _this.update($(this));
        $('.list .row textarea[data-set-key="' + $(this).attr('data-set-key') + '"][data-set-language="' + $(
          this).attr('data-set-language') + '"]').val($(this).val());
      });
    },
    deletes: function(el, data) {
      $.get('./api.php?action=deleteMi18n&key=' + data.attr('data-set-key'), function(result) {
        result = JSON.parse(result);
        if (result.status == '200') {
          el.parent().parent().parent().fadeOut(function() {
            $(this).remove();
          });
        } else {
          el.parent().parent().find('.status').text(result.message);
          setTimeout(function() {
            el.parent().parent().find('.status').fadeOut();
          }, 5000);
        }
      });
    },
    // 更新翻译内容
    update: function(el) {
      el.parent().parent().find('.status').text('修改中...').show();
      var data = {
        'key': el.attr('data-set-key'),
        'language': el.attr('data-set-language'),
        'content': el.val()
      };
      $.post('./api.php?action=updateMi18n', data, function(result) {
        result = JSON.parse(result);
        el.parent().parent().find('.status').text(result.message);
        setTimeout(function() {
          el.parent().parent().find('.status').fadeOut();
        }, 5000);
      });
    },
    // 导出全部翻译内容
    exportMi18n: function(format, language) {
      $('.content .export').show();
      $.get('./api.php?action=getMi18n', function(result) {
        if (format == 'json') {
          $('.content .export textarea').val(result);
        } else {
          result = JSON.parse(result);
          var text = '';
          for (var i in result) {
            text += result[i].key + "=" + (result[i][language] ? result[i][language] : result[i]['source']).replace(/""/g,'\"') + ";\r\n";
          }
          $('.content .export textarea').val(text);
        }
      });

      $('.content .export .background, .content .export .close').click(function() {
        $('.content .export').hide();
      });
    },
    // 导入翻译内容
    importMi18n: function() {
      $('.content .import').show();
      /*
      $.get('./api.php?action=getMi18n', function(result){
        result = JSON.parse(result);
        $('.content .export textarea').val(result);
      });
      */
      $('.content .import .background, .content .import .close').click(function() {
        $('.content .import').hide();
      });
    },
    // 获取翻译列表
    getList: function(page) {
      var ___this = _this = this;
      $.get('./api.php?action=getListMi18n&limit=20&page=' + page, _this.search, function(result) {
        result = JSON.parse(result);
        var list = result.list;
        var pagination = result.pagination;
        if (list.length > 0) {
          var sourceLanguageHtml, rowhtml, columnHtml = '';
          $('.content .list').empty();
          for (var i in list) {
            rowhtml = '<div class="row">';
            for (var ii in list[i]) {
              if (ii == 'key' || ii == 'page') {
                continue;
              }
              var translated = list[i][ii] == list[i]["source"] ? 'no-translation' : 'translated';
              if (ii == 'source') {
                sourceLanguageHtml = '<dl class="width ' + ii + ' ' + translated +
                  '" data-set-language="' + ii + '">';
                sourceLanguageHtml += '<dt><strong>' + _this.languageIndex[ii] + ' - ' + ii +
                  '</strong> <a href="#none" data-set-id="1623" class="fa fa-trash-o delete-button" title="删除"></a><a href="#none" data-set-id="1623" class="preview-button fa fa-window-maximize" aria-hidden="true"></a></dt>';
                sourceLanguageHtml += '<dd><textarea data-set-key="' + list[i].key +
                  '" data-set-language="' + ii + '" data-set-page="' + list[i].page +
                  '" data-set-created-datetime="' + list[i].created_datetime +
                  '" data-set-last-update-datetime="' + list[i].last_update_datetime +
                  '" data-set-action="preview" disabled="disabled">' + list[i][ii] + '</textarea></dd>';
                sourceLanguageHtml += '</dl>';
              } else if (_this.languageIndex[ii]) {
                if (_this.expandColumn.indexOf(ii) != -1) {
                  columnHtml += '<dl class="width ' + ii + ' ' + translated + '" data-set-language="' + ii +
                    '">';
                  columnHtml += '<dt><strong class="expand fa fa-expand"> ' + _this.languageIndex[ii] +
                    '</strong><span> - ' + ii + ' </span><span class="status">' + (list[i][ii] == list[i]
                      ["source"] ? "<i class=\"no-translation fa fa-times\" aria-hidden=\"true\"></i>" :
                      "<i class=\"translated fa fa-check-circle\" aria-hidden=\"true\"></i>") +
                    '</span><a href="#none" class="fa fa-language translate-button" data-set-language="'+ii+'" aria-hidden="true"></a><a href="#none" class="edit-button fa fa-window-maximize" aria-hidden="true"></a></dt>';
                  columnHtml += '<dd><textarea data-set-key="' + list[i].key + '" data-set-language="' +
                    ii + '" data-set-page="' + list[i].page + '" data-set-created-datetime="' + list[i].created_datetime +
                    '" data-set-last-update-datetime="' + list[i].last_update_datetime + '">' + list[i][
                      ii
                    ] + '</textarea></dd>';
                } else {
                  columnHtml += '<dl class="' + ii + ' ' + translated + '" data-set-language="' + ii +
                    '">';
                  columnHtml += '<dt><strong class="expand fa fa-compress"> ' + _this.languageIndex[ii] +
                    '</strong><span style="display:none"> - ' + ii +
                    ' </span><span class="status" style="display:none">' + (list[i][ii] == list[i][
                        "source"
                      ] ? "<i class=\"no-translation fa fa-times\" aria-hidden=\"true\"></i>" :
                      "<i class=\"translated fa fa-check-circle\" aria-hidden=\"true\"></i>") +
                    '</span><a href="#none" class="fa fa-language translate-button" style="display:none" data-set-language="'+ii+'" aria-hidden="true"></a><a href="#none" style="display:none" class="edit-button fa fa-window-maximize" aria-hidden="true"></a></dt>';
                  columnHtml += '<dd style="display:none"><textarea data-set-key="' + list[i].key +
                    '" data-set-language="' + ii + '" data-set-page="' + list[i].page +
                    '" data-set-created-datetime="' + list[i].created_datetime +
                    '" data-set-last-update-datetime="' + list[i].last_update_datetime + '">' + list[i][
                      ii
                    ] + '</textarea></dd>';
                }
                columnHtml += '</dl>';
              }
            }
            rowhtml += sourceLanguageHtml + columnHtml + '</div>';
            $('.content .list').append(rowhtml);
            columnHtml = '';
          }

          function expand(_this, __this){
            var column = $(_this).parent().parent().attr('data-set-language');
            if ($(_this).hasClass('fa-expand')) {
              for (var i in __this.expandColumn) {
                if (__this.expandColumn[i] == column) __this.expandColumn.splice(i, 1);
              }
              $(_this).removeClass('fa-expand').addClass('fa-compress');
              $('.content .list .row dl.' + column).removeClass('width');
              $('.content .list .row dl.' + column + ' dt strong').removeClass('fa-expand').addClass('fa-compress');
              $('.content .list .row dl.' + column + ' dt :not(strong)').fadeOut();
              $('.content .list .row dl.' + column + ' dd').fadeOut();
            } else {
              // 收缩其余语言项
              $(_this).removeClass('fa-expand').addClass('fa-compress');
              $('.content .list .row dl:not(.source)').removeClass('width');
              $('.content .list .row dl:not(.source) dt strong').removeClass('fa-expand').addClass('fa-compress');
              $('.content .list .row dl:not(.source) dt :not(strong)').fadeOut();
              $('.content .list .row dl:not(.source) dd').fadeOut();
              // 展开点击语言项
              __this.expandColumn = [];
              __this.expandColumn.push(column);
              $(_this).removeClass('fa-compress').addClass('fa-expand');
              $('.content .list .row dl.' + column).addClass('width');
              $('.content .list .row dl.' + column + ' dt strong').removeClass('fa-compress').addClass('fa-expand');
              $('.content .list .row dl.' + column + ' dt :not(strong)').fadeIn();
              $('.content .list .row dl.' + column + ' dd').fadeIn();
            }
          }
          $('.content .list .row dt .expand').click(function() {
            expand($(this), _this);
          });
          $('.content .list .row dt .delete-button').click(function() {
            _this.deletes($(this), $(this).parent().parent().find('textarea'));
          });
          $('.content .list .row dt .translate-button').click(function() {
            var _this = this;
            Translate.run(
            {
              q: $(this).parent().parent().parent().find('.source textarea').val(),
              to: $(this).attr('data-set-language')
            },
            function(data){
              $(_this).parent().parent().find('textarea').val(data.trans_result[0].dst);
              ___this.update($(_this).parent().parent().find('textarea'));
            });
          });
          $('.content .list .row dt .edit-button').click(function() {
            _this.edit($(this).parent().parent().find('textarea'));
          });
          $('.content .list .row dt .preview-button').click(function() {
            _this.edit($(this).parent().parent().find('textarea'));
          });
          $('.content .list .row textarea').change(function() {
            _this.update($(this));
          });
          $('.content .list .row textarea').focusin(function() {
            $(this).css({
              color: '#333'
            });
          });
          $('.content .list .row textarea').focusout(function() {
            $(this).css({
              color: '#999'
            });
          });
        } else {
          $('.content .list').html(
            '<div style="width:100%; height:400px; line-height:400px; text-align:center; font-size:16px">暂无数据......</div>'
          );
        }
        if (pagination) {
          $('#pagination .begin').attr('data-set-page', pagination.begin);
          $('#pagination .previous').attr('data-set-page', pagination.previous);
          $('#pagination .next').attr('data-set-page', pagination.next);
          $('#pagination .end').attr('data-set-page', pagination.end);
          var current = '';
          $('#pagination .page-list').empty();
          for (var i = pagination.begin; i < pagination.end + 1; i++) {
            current = i == pagination.page ? 'class="current"' : '';
            $('#pagination .page-list').append('<a href="#none" ' + current + ' data-set-page="' + i +
              '">' + i + '</a>');
          }
          $('#pagination .total-page').text(pagination.totalPage);
          $('#pagination .total-row').text(pagination.totalRow);
          $('nav .left .total-row').text(pagination.totalRow);

          $('#pagination a').off('click').on('click', function() {
            _this.getList($(this).attr('data-set-page'));
          });

          if (pagination.totalRow > 0) {
            $('#pagination').show();
          } else {
            $('#pagination').hide();
          }
        } else {
          $('#pagination').hide();
        }
      });
    }
  },
  init: function() {
    var _this = this;
    // 语种
    $.get('./api.php?action=getLanguage', function(result) {
      result = JSON.parse(result);
      for (var i in result) {
        _this.language.languageIndex[result[i].index] = result[i].name;
        $('.content .export .text .format-text').append('<a href="#none" data-set-language="' + result[i]
          .index + '">' + result[i].name + '</a>&nbsp;&nbsp;');

        $('.filter .search .search-field').append('<option value="'+result[i].index+'">'+result[i].name+'</option>');
      }
      // 导出格式
      $('.content .export .text .format-text a').click(function() {
        _this.language.exportMi18n('text', $(this).attr('data-set-language'));
      });
      // 输出翻译列表
      $.get('./api.php?action=isLogin', function(result) {
        result = JSON.parse(result);
        if (result.status == '200') {
          _this.language.getList(1);
        }
      });
    });
    // 给导航条绑定事件
    // 管理员
    _this.admin.init();
    // 网站
    $('nav .nav-website').click(function() {
      _this.website.init();
    });
    // 语种管理
    $('nav .nav-language').click(function() {
      _this.languageManage.init();
    });
    // 清空
    $('nav .nav-delete-all').click(function() {
      var deleteAllMi18n = confirm("确定清空全部翻译数据吗?");
      if (deleteAllMi18n){
        $.get('./api.php?action=deleteAllMi18n', function(result) {
          result = JSON.parse(result);
          if (result.status == '200') {
            alert('已全部清空');
            window.location.reload();
          } else {
            alert('清空失败！');
          }
        });
      }
    });
    // 导出
    $('nav .nav-export, .content .export .text .format-json').click(function() {
      _this.language.exportMi18n('json');
    });
    $('.content .export .text .gen-language-index').click(function() {
      $(this).siblings('.language-index').text(Mi18n.keygen($(this).siblings('.language-text').val()));
    });

    // 导入
    $('nav .nav-import').click(function() {
      _this.language.importMi18n();
    });
    // 过滤
    for (var i in this.language.searchField) {
      $('.filter .search .search-field').append('<option value="'+i+'">'+this.language.searchField[i]+'</option>');
    }
    // 过滤已翻译与未翻译的
    $('.filter .right .all').click(function() {
      $('.content .list .row dl.translated dd textarea').fadeIn();
      $('.content .list .row dl.no-translation dd textarea').fadeIn();
    });
    $('.filter .right .no-translation').click(function() {
      $('.content .list .row dl.translated dd textarea').fadeOut();
      $('.content .list .row dl.no-translation dd textarea').fadeIn();
    });
    $('.filter .right .translated').click(function() {
      $('.content .list .row dl.translated[data-set-language != "source"] dd textarea').fadeIn();
      $('.content .list .row dl.no-translation[data-set-language != "source"] dd textarea').fadeOut();
    });
    // 网站
    $.get('./api.php?action=getWebsite', function(result) {
      _this.result = JSON.parse(result);
      for (var i in _this.result) {
        $('.filter .search .search-website').append('<option value="' + _this.result[i]['id'] + '">' +
          _this.result[i]['domain'] + '</option>');
      }
    });
    $('.filter .search input[type="button"]').click(function() {
      _this.language.search = {
        'field': $(this).siblings('.search-field').val(),
        'website': $(this).siblings('.search-website').val(),
        'sc': $(this).siblings('.search-sc').val()
      }
      _this.language.getList(1);
    });
    $('.filter .search .get-all').click(function() {
      _this.language.search = {
        'field': '',
        'sc': ''
      }
      _this.language.getList(1);
    });
  }
}
$(function() {
  Mi18nAdmin.init();
});
